package br.com.inventario.relatorios;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRXmlDataSource;

/** Classe base abstrata de Servlet que produz um arquivo PDF
 *  a partir de um relatorio do JasperReports */
@SuppressWarnings("serial")
public abstract class GeradorRelatorioPDF extends HttpServlet {

	/** Nome do arquivo XML a ser usado como DataSource para o relatorio */
	protected String dataSourceFilename; 
	/** Nome do arquivo Jasper do relatorio */
	protected String jasperReportFilename; 
	/** Caminho XPath dos dados que preenchem o relatorio */
	protected String reportDataSourceXPath;

	/** Requisicao GET: simplesmente chama o metodo que trata a requisicao POST.
	 *  @param request Requisicao HTTP
	 *  @param response Resposta HTTP
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/** Requisicao POST: Gera o PDF a partir do arquivo Jasper
	 *  @param request Requisicao HTTP
	 *  @param response Resposta HTTP
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String path = getServletContext().getRealPath("/");

		ServletOutputStream servletOutputStream = response.getOutputStream();
		
		File reportFile = new File(path + "/" + jasperReportFilename);
		File dataFile = new File(path + "/" + dataSourceFilename);

		byte[] rawPDF = null;

		try {
			
			HashMap<String, String> parameters = new HashMap<String, String>();
			parameters.put("SUBREPORT_DIR", path);
			
			JRXmlDataSource dataSource = new JRXmlDataSource(dataFile, reportDataSourceXPath);
			
			rawPDF = JasperRunManager.runReportToPdf(reportFile.getPath(), parameters, dataSource);

			response.setContentType("application/pdf");
			response.setContentLength(rawPDF.length);

			servletOutputStream.write(rawPDF, 0, rawPDF.length);
			
			servletOutputStream.flush();
			servletOutputStream.close();

		} catch(Exception e){
			e.printStackTrace();
		}
	}
}
